package com.aop.log.aspect;

import com.alibaba.fastjson.JSON;
import com.aop.log.utils.IpUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;


@Aspect
@Component
@Slf4j
public class WebLogAspect {

    // 以自定义 @WebLog 注解为切点
    @Pointcut("@annotation(com.aop.log.aspect.WebLog)")

    public void webLog() { }

    // 在切点之前织入
    @Before(value = "webLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        // 获取 @WebLog 注解的描述信息
        String methodDescription = getAspectLogDescription(joinPoint);
        log.info("\n");
        log.info("----------------------切点织入开始-"+methodDescription+"-------------------------");
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

        HttpServletRequest request = attributes.getRequest();

        // 打印请求 url
        log.info("==>  URL            : {}", request.getRequestURL().toString());
        // 打印描述信息
        log.info("==>  Description    : {}", methodDescription);
        // 打印 Http method
        log.info("==>  HTTP Method    : {}", request.getMethod());
        // 打印调用 controller 的全路径以及执行方法
        log.info("==>  Class Method   : {}.{}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());
        // 打印请求的 IP  request.getRemoteAddr()
        log.info("==>  IP             : {}",  IpUtils.getLocalIp4Address().get().toString().replaceAll("/",""));
        // 打印请求入参
        log.info("==>  Request Args   : {}", JSON.toJSONString(joinPoint.getArgs()));
    }

    // 在切点之后织入
    @After("webLog()")
    public void doAfter(JoinPoint joinPoint) throws Throwable {
        // 获取 @WebLog 注解的描述信息
        String methodDescription = getAspectLogDescription(joinPoint);
        log.info("----------------------切点织入结束-"+methodDescription+"-------------------------");
    }


    // 环绕
    @Around("webLog()")
    public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
       // long startTime = System.currentTimeMillis();
       Object result = proceedingJoinPoint.proceed();
        // 打印出参
       //log.info("==>  Response Args  : {}", JSON.toJSONString(result));
       // 执行耗时
       // log.info("==>  Time-Consuming : {} ms", System.currentTimeMillis() - startTime);
       // log.info("----------------------打印出参结束-------------------------");
        return result;
    }

    @AfterReturning("webLog()")
    public void doAfterReturning(JoinPoint joinPoint) throws Throwable {
        //log.info("----------------------返回通知-------------------------");
        //String methodName = joinPoint.getSignature().getName();
        //log.info("==>  Signature name  : {}", joinPoint.getSignature().getName());
        //WriteErrorToLog4J("afterMethod is exexuting the method ： " + methodName);
    }

    @AfterThrowing(value = "webLog()", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, Throwable e) throws Exception {
        log.error("==>  异常通知:  {}", e.getMessage());
    }


    // 获取切面注解的描述
    public String getAspectLogDescription(JoinPoint joinPoint) throws Exception {
        String targetName  = joinPoint.getTarget().getClass().getName();
        String methodName  = joinPoint.getSignature().getName();
        Object[] arguments = joinPoint.getArgs();
        Class targetClass  = Class.forName(targetName);
        Method[] methods = targetClass.getMethods();
        StringBuilder description = new StringBuilder("");
        for (Method method : methods) {
            if (method.getName().equals(methodName)) {
                Class[] clazz = method.getParameterTypes();
                if (clazz.length == arguments.length) {
                    description.append(method.getAnnotation(WebLog.class).description());
                    break;
                }
            }
        }
        return description.toString();
    }










//    //    把正常信息信息写进日志里面
//    public void WriteErrorToLog4J(String message)throws IOException {
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        try {
//            FileWriter fw = new FileWriter(filePath, true);//如果追加方式用true
//            BufferedWriter bw = new BufferedWriter(fw);
//            String messageStr = new String(message.getBytes(StandardCharsets.UTF_8));
//
//            bw.append("-----------" + sdf.format(new Date()) + "------------\r\n");// 往已有的文件上添加字符串
//            bw.append(messageStr + "\n ");
//
//            bw.flush();
//            bw.close();
//            fw.close();
//        } catch (Exception e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }
//    }
//
//    /**
//     *
//     * @param detailErrMsg 详细错误信息
//     * @param joinPoint 方法名称
//     * @Description: 日志异常
//     * @author： Ma
//     * @createTime： 2016-10-14
//     */
//    public void writeLog(String detailErrMsg,JoinPoint joinPoint,Exception ex){
//
//        HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.
//                getRequestAttributes()).getRequest();
//        //获取请求的URL
//        StringBuffer requestURL = request.getRequestURL();
//        //获取参 数信息
//        String queryString = request.getQueryString();
//        //封装完整请求URL带参数
//        if(queryString != null){
//            requestURL .append("?").append(queryString);
//        }
//
//        String cla=joinPoint.getTarget().getClass().getName();//action
//        String method=joinPoint.getSignature().getName();//method
//        try{
//
//            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//            //创建输出异常log日志
////            File file =new File(filePath);
////            //if file doesnt exists, then create it
////            if(!file.exists()){
////                file.createNewFile();
////            }
//            FileWriter fw = new FileWriter(filePath, true);
//            BufferedWriter bw = new BufferedWriter(fw);
//
////            FileOutputStream out=new FileOutputStream(file,false);
//            //日志具体参数
//            StringBuffer sb=new StringBuffer();
//            sb.append("-----------"+sdf.format(new Date())+"------------\r\n");
//            sb.append("远程请求URL["+requestURL+"]\r\n");
//            sb.append("接口方法：["+cla+"."+method+"]\r\n");
//            sb.append("详细错误信息："+ex+"\r\n");
//            sb.append(detailErrMsg+"\r\n");
//
////            sb.toString().getBytes("utf-8")
//            bw.append(new String(sb.toString().getBytes("utf-8"))+"\r\n");//注意需要转换对应的字符集
//            bw.close();
//            fw.close();
//        }catch(IOException e){
//            e.printStackTrace();
//        }
//
//
//    }

}
